package com.cheetah.start.monitor.logfile.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.file.FileReader;
import com.cheetah.start.common.annotation.ApiCount;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.base.result.ResultTable;
import com.cheetah.start.common.query.PageQuery;
import com.cheetah.start.monitor.logfile.domain.LogFileDo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 日志文件控制器
 *
 * @author Feel
 * @date 2021/08/21
 */
@Api(tags = "日志文件")
@Slf4j
@ApiCount
@CrossOrigin
@Validated
@RestController
@RequestMapping("/logfile")
public class LogFileController extends ResultController {

    /** 日志文件夹路径 */
    @Value("${logpath}")
    private String logPath;

    /**
     * 列表
     *
     * @param pageQuery 页面查询
     * @return {@link ResultTable}
     */
    @GetMapping("/list")
    public ResultTable list(PageQuery pageQuery) {
        File file = new File(logPath);
        List<LogFileDo> fileDoList = new ArrayList<>();
        for (File listFile : file.listFiles()) {
            LogFileDo logFileDo = new LogFileDo();
            String fileName = listFile.getName();
            long length = listFile.length();
            String path = listFile.getPath();
            logFileDo.setFileName(fileName);
            logFileDo.setSize(length / 1024);
            logFileDo.setFilePath(path);
            fileDoList.add(logFileDo);
        }
        int size = fileDoList.size();
        List<LogFileDo> page = CollUtil.page(pageQuery.getPage() - 1, pageQuery.getLimit(), fileDoList);
        return pageTable(page, size);
    }

    /**
     * 读取文件内容
     *
     * @param path 路径
     * @return {@link Result}
     */
    @GetMapping("/read")
    public Result read(@NotBlank(message = "文件路径不能为空") String path) {
        FileReader fileReader = new FileReader(path);
        List<String> strings = fileReader.readLines();
        // 只给看最新 100 行，不然页面很慢很卡
        if (strings.size() < 100) {
            return success("成功", strings);
        } else {
            List<String> stringList = strings.subList(strings.size() - 100, strings.size() - 1);
            return success(stringList);
        }
    }

}
